package com.smartwebx.fr.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

/**
 * 微信
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/weChat")
public class WeChatController {

	private final String token = "linxi246";

	@RequestMapping(value = "/validate")
	@ResponseBody
	public void getSimpleData(HttpServletResponse response, String signature, String timestamp, String nonce,
			String echostr) throws Exception {
		List<String> sortList = Lists.newArrayList(token, timestamp, nonce);
		Collections.sort(sortList);
		String sortStr = Joiner.on("").join(sortList);
		String mytoken = SHA1(sortStr);

		// String result = "";
		if (mytoken != null && mytoken != "" && mytoken.equals(signature)) {
			System.out.println("签名校验通过。");
			response.getWriter().println(echostr); // 如果检验成功输出echostr，微信服务器接收到此输出，才会确认检验完成。
		} else {
			System.out.println("签名校验失败。");
		}

		// return result;
	}

	private static String SHA1(String decript) {
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-1");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

}
